﻿/**
 * Created by Administrator on 2017/8/18 0018.
 */
var express = require('express');
var svgCaptcha = require('svg-captcha');
var crypto = require("crypto");
var multer = require("multer");
var http = require("http");
var qr = require('qr-image')
var qs = require("querystring");
var jwt = require('jsonwebtoken');
var request = require('request');
let path = require('path');
let fs = require('fs');
var uuid = require("uuid");
let moment = require('moment');
var db = require('../db/db.js');
var config = require('../config');
var wx = require('../util/wx');
var images = require("images");
var log = require("../util/logger");
var gm = require('gm')
const MAO = require('multer-aliyun-oss');
const cache = require('memory-cache')


var wx_applets = require("../util/wx_applets.js");

var person_model = require("../model/person");

const ossupload = multer({
    storage: MAO({
        config: {
            region: 'oss-cn-beijing',
            accessKeyId: 'LTAI4GL383KpSFQJReEpNusz',
            accessKeySecret: 'uLukwSKWuEBctg3REaCZhVAsoupkJE',
            bucket: 'fantuanjiang'
        }
    })
});



var router = express.Router();   /*可使用 express.Router 类创建模块化、可挂载的路由句柄*/

var storage = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, '../uploads');
    },
    filename: function (req, file, cb) {
        cb(null, `${Date.now()}-${file.originalname}`)
    }
})




var storagemy = multer.diskStorage({
    destination: function (req, file, cb) {
        cb(null, './uploads');
    },
    filename: function (req, file, cb) {
        var pathstr = path.join(__dirname, "../uploads/" + moment().format('YYYYMMDD'));
        console.log("pathstr", pathstr);
        if (fs.existsSync(pathstr)) {
            cb(null, moment().format('YYYYMMDD') + "/" + `${Date.now()}-${file.originalname}`)

        } else {
            fs.mkdirSync(pathstr);
            cb(null, moment().format('YYYYMMDD') + "/" + `${Date.now()}-${file.originalname}`)
        }


    }
})



var uploadmy = multer({ storage: storagemy });



router.get('/code', function (req, res) {
    const cap = svgCaptcha.createMathExpr();
    req.session.captcha = cap.text; // session 存储
    res.type('svg'); // 响应的类型
    res.send(cap.data);

})


/**
 * 登录
 * @route POST /login
 * @summary 登录
 * @group 管理后台
 * @param {string} username.formData - 用户名默认admin
 * @param {string} password.formData   密码默认admin
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/login', async function (req, res) {

    var username = req.body.username;
    var password = req.body.password;


    var password = crypto.createHash("sha1").update(password).digest("hex");
    var superinfo = await db.query("select *  from manage where username=? and password=?", [username, password]);
    if (superinfo.length > 0) {

        let content = { id: superinfo[0].id + "", jiaoseid: superinfo[0].jiaoseid }; // 要生成token的主题信息
        let secretOrPrivateKey = config.token.secretOrPrivateKey; // 这是加密的key（密钥） 
        let token = jwt.sign(content, secretOrPrivateKey, {
            expiresIn: 60 * 60 * 24 * 30
        });

        var result = {
            "status": 200,
            "message": "登录成功",
            "data": {
                "token": token,
                mid: superinfo[0].mid,
                username: superinfo[0].username,
                truename: superinfo[0].truename,
                jiaoseid: superinfo[0].jiaoseid
            }
        }
        res.jsonp(result);

    } else {
        var result = {
            "status": 400,
            "message": "用户名密码不正确",

        }
        res.jsonp(result);


    }




    //  }

    //res.redirect('home');


})




/**
 * 上传图片
 * @group H5
 * @route POST /upload/file
 * @summary 上传图片
 * @param {string} imgFile 图片
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post('/upload/file', ossupload.single('imgFile'), function (req, res) {
    // 读取上传的图片信息
    log.info(JSON.stringify(req.file))
    console.log(req.file);
    // images("input.jpg")                     //Load image from file 
    //     //加载图像文件
    //     .size(400)                          //Geometric scaling the image to 400 pixels width
    //     //等比缩放图像到400像素宽
    //     //在(10,10)处绘制Logo
    //     .save("output.jpg", {               //Save the image to a file,whih quality 50
    //         quality: 50                    //保存图片到文件,图片质量为50
    //     });

    res.json({
        code: 200,
        message: '上传成功',
        pic: config.url + "/uploads/" + req.file.filename,
        file: "/uploads/" + req.file.filename
    })
})


router.post('/upload/file2', ossupload.single('imgFile'), function (req, res) {
    // 读取上传的图片信息
    console.log(req.file);
    res.json({
        error: 0,
        message: '上传成功',
        url: req.file.url

    })
})


router.post('/uploadImg', ossupload.single('imgFile'), async function (req, res) {
    // 读取上传的图片信息
    console.log("dd");
    console.log(req.file);



    res.json({
        code: 200,
        message: '上传成功',
        pic: req.file.url,
        file: req.file.url
    })


})


//登录
router.get('/login', async function (req, res) {
    var arr1 = [];
    var arr2 = [];
    var imgday = await db.query("select *  from system_loginimg where state=1 and type='day'", []);
    for (var i = 0; i < imgday.length; i++) {
        var object = {};
        object.src = imgday[i].imgurl;
        object.mcolor = imgday[i].btncolor;
        arr1.push(object);
    }
    var imgnight = await db.query("select *  from system_loginimg where state=1 and type='night'", []);
    for (var i = 0; i < imgnight.length; i++) {
        var object = {};
        object.src = imgnight[i].imgurl;
        object.mcolor = imgnight[i].btncolor;
        arr2.push(object);
    }
    var obj = {
        day: arr1,
        night: arr2
    };
    var str = JSON.stringify(obj);


    console.log(str);
    res.render('login', { str: str, config: config });

})



/**
 * 微信小程序登录
 * @group 微信小程序登录
 * @route POST /wxapplet/login
 * @summary 微信小程序登录
 * @param {string} code.formData code
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */

router.post('/wxapplet/login', function (req, res) {


    var req_params = {
        "appid": config.wxpay.appid,
        "secret": config.wxpay.secret,
        "js_code": req.body.code,
        "grant_type": 'authorization_code'
    }
    var content = qs.stringify(req_params);
    console.log(content);
    var url = "https://api.weixin.qq.com/sns/jscode2session?" + content;

    request({ url: url, method: 'GET' }, function (error, response, body) {
        console.log('error:', error); // Print the error if one occurred
        console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
        console.log('body:', body);
        if (!error && response.statusCode == 200) {
            console.log(body);

            var info = JSON.parse(body);


            res.json({
                status: 200,
                message: 'success',
                data: info

            })



        }

    });



});



/**
 * 微信小程序登录
 * @group 微信小程序
 * @route POST /wxapplet/reg
 * @summary 微信小程序登录
 * @param {string} open_id.formData open_id
 * @param {string} nickname.formData 昵称
 * @param {string} gender.formData 1男2女
 * @param {string} avatarurl.formData 头像
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */

router.post('/wxapplet/reg', async function (req, res) {


    if (req.body.open_id == "") {
        res.json({
            status: 400,
            message: 'open_id是空',
            data: ""

        })
        return;
    }

    var data = req.body;
    data.create_time = new Date();
    data.type = 3;
    console.log("data", data);
    var userinfo = await user_model.getinfo("open_id='" + req.body.open_id + "' and type=3");
    if (userinfo.length == 0) {
        var obj = await user_model.add(data);
        if (obj.code == 200) {

            var userid = obj.msg.insertId;
            var content = { userid: userid + "" }; // 要生成token的主题信息
            var secretOrPrivateKey = config.token.secretOrPrivateKey; // 这是加密的key（密钥） 
            var token = jwt.sign(content, secretOrPrivateKey, {
                expiresIn: 60 * 60 * 12  // 1小时过期
            });

            res.json({
                status: 200,
                message: 'success',
                data: token

            })

        }
    } else {

        var userid = userinfo[0].user_id;
        var content = { userid: userid + "" }; // 要生成token的主题信息
        var secretOrPrivateKey = config.token.secretOrPrivateKey; // 这是加密的key（密钥） 
        var token = jwt.sign(content, secretOrPrivateKey, {
            expiresIn: 60 * 60 * 12  // 1小时过期
        });



        res.json({
            status: 200,
            message: 'success',
            data: token

        })


    }




});



router.get('/test', async function (req, res) {
    var message = [];
    //返回error  牙医系统就崩溃
    res.send("123");
});

/**
 * 二维码
 * @group 二维码
 * @route POST /qr
 * @summary 二维码
 * @param {string} text.formData 名称
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.post("/qr", async function (req, res) {

    var text = req.body.text;
    var img = qr.image(text, { size: 10 });

    var imgName = +(new Date()) + '' + Math.ceil(Math.random() * 89 + 10);
    imgName = path.join(__dirname, "../uploads/" + imgName);
    var qr_pipe = img.pipe(fs.createWriteStream(imgName));
    qr_pipe.on('finish', function () {
        console.log("imgName", imgName);
        var bitmap = fs.readFileSync(imgName);
        var base64str = Buffer.from(bitmap, 'binary').toString('base64');

        var base64 = "data:image/png;base64," + base64str;
        console.log("base64", base64);


        var result = {
            "status": 200,
            "message": "",
            data: base64

        }
        res.jsonp(result);

    });

});


/**
 * 二维码
 * @group 二维码
 * @route GET /qr
 * @summary 二维码
 * @param {string} text.formData 名称
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */
router.get("/qr", async function (req, res) {

    var text = req.query.text;
    var img = qr.image(text, { size: 10 });
    res.writeHead(200, { 'Content-Type': 'image/png' });
    img.pipe(res);
});

/**
 * 小程序二维码
 * @group 二维码
 * @route POST /createwxaqrcode
 * @summary 小程序二维码
 * @param {string} id.formData 商品ID
 * @returns {object} 200 - An array of user info
 * @returns {Error}  default - Unexpected error
 */

router.get("/createwxaqrcode", async function (req, res) {
    console.log(req.body);
    var accessToken = await wx_applets.gettoken();
    var token = accessToken.access_token;
    var uid = uuid.v1();
    var id = uid.replace(/\-/g, '');


    var data = id;
    var pathstr = "pages/address/create";
    var filename = new Date().valueOf();

    var data = await wx_applets.createwxaqrcode(data, pathstr, token, filename);

    console.log("data", data);



    var filePath = path.join(__dirname, "../uploads/shop/" + filename + ".jpg");


    var file = fs.readFileSync(filePath);
    var base64str = new Buffer(file).toString('base64');

    var base64 = "data:image/png;base64," + base64str;
    console.log("base64", base64);


    res.send("<img src='" + base64 + "'>");


});

router.post("/getdata", async function (req, res) {

    var obj = await db.query("select * from mycache where keystr=?", [req.body.id]);

    if (obj.length > 0) {
        var result = {
            "status": "200",
            "message": "success",
            "data": obj[0].value
        }
        res.jsonp(result);
    } else {
        var result = {
            "status": "400",
            "message": "err",
        }
        res.jsonp(result);

    }



});

router.post("/wx", async function (req, res) {
    console.log(req.body);
    var accessToken = await wx_applets.gettoken();
    var token = accessToken.access_token;


    var data = req.body.id;
    var pathstr = "pages/index/index";
    var filename = new Date().valueOf();

    var data = await wx_applets.createwxaqrcode(data, pathstr, token, filename);


    var filePath = path.join(__dirname, "../uploads/shop/" + filename + ".jpg");


    var file = fs.readFileSync(filePath);
    var base64str = new Buffer(file).toString('base64');

    var base64 = "data:image/png;base64," + base64str;
    console.log("base64", base64);


    var result = {
        "status": 200,
        "message": "",
        data: base64

    }
    res.jsonp(result);



});

router.get("/test", async function (req, res) {

    res.send("123");
});


router.get("/success", async function (req, res) {
    res.send("支付成功");
});

function downloadFileAsync(uri, dest) {
    return new Promise((resolve, reject) => {
        // 确保dest路径存在
        const file = fs.createWriteStream(dest);

        http.get(uri, (res) => {
            if (res.statusCode !== 200) {
                resolve(res.statusCode);
                return;
            }

            res.on('end', () => {
                console.log('download end');

            });

            // 进度、超时等

            file.on('finish', () => {
                console.log('finish write file')
                file.close(resolve);
                resolve("success");
            }).on('error', (err) => {
                fs.unlink(dest);
                reject(err.message);
            })

            res.pipe(file);
        });
    });
}
router.post("/myqr", async function (req, res) {
    var accessToken = await wx_applets.gettoken();
    var token = accessToken.access_token;
    var uid = uuid.v1();
    var filename = uid.replace(/\-/g, '');


    var personurl = path.join(__dirname, "../uploads/person");

    var result = await downloadFileAsync(req.body.url, personurl + "/" + filename + ".jpg");

    console.log("result", result);

    var ss = await wx_applets.createwxaqrcode(req.body.id, "pages/goods/index", token, filename);
    console.log("ss", ss);
    var waterImg = path.join(__dirname, "../uploads/" + filename + ".jpg");

    var base_image_url = personurl + "/" + filename + ".jpg";
    var output_file = path.join(__dirname, "../uploads/personok") + "/" + filename + ".jpg";


    gm()
        .in('-resize', '600x600')// 设置微信二维码图片的大小（等比缩放）
        .in('-page', '0,0')// -page是设置图片位置，所有的图片以左上为原点，向右、向下为正
        .in(base_image_url)// 底图，到这里第一张图就设置完了，要先设置参数，再设置图片
        .in('-resize', '150x150')// 设置微信二维码图片的大小（等比缩放）
        .in('-page', '+450+450')// 设置微信二维码图片的位置
        .in(waterImg)// 二维码图
        // .in('-page', '+210+532')// logo图位置
        // .in(n)// logo图
        .mosaic()// 图片合成
        .write(output_file, function (err) { // 图片写入
            if (err) {
                console.log(err);

            } else {
                console.log('ok');

                var result = {
                    "status": 200,
                    "message": "",
                    data: config.url + "/uploads/personok/" + filename + ".jpg"

                }
                res.jsonp(result);


            }
        });






});

async function test() {
    var accessToken = await wx_applets.gettoken();
    var token = accessToken.access_token;
    var uid = uuid.v1();
    var filename = uid.replace(/\-/g, '');

    var ss = await wx_applets.createwxaqrcode(1, "pages/goods/index", token, filename);
    console.log("ss", ss);
    var filePath = path.join(__dirname, "../uploads/" + filename + ".jpg");


    var file = fs.readFileSync(filePath);
    var base64str = new Buffer(file).toString('base64');

    var base64 = "data:image/png;base64," + base64str;
    console.log("base64", base64);

}
//test();


module.exports = router;   /*暴露这个 router模块*/
